﻿/// <reference path="../Scripts/MicrosoftAjax.debug.js" />

(function () {
    var scriptName = "RegisterBehavior";
    var e = null;

    function execute() {

        Type.registerNamespace("SCS");

        SCS.RegisterBehavior = function (element) {
            SCS.RegisterBehavior.initializeBase(this, [element]);

            this._stepIndex = 0;
            this._buttonClickDelegate = null;
            this._validateDelegate = null;
            this._pendingAction = null;
            this._lazyValidate = true;
            this._root = null;
            this._hostInfo = null;
        }

        SCS.RegisterBehavior.prototype = {
            initialize: function () {
                SCS.RegisterBehavior.callBaseMethod(this, 'initialize');

                this._root = $get("registerForm");
                eval("this._hostInfo = " + $(this._root).attr("dialog-host"));

                this._buttonClickDelegate = Function.createDelegate(this, this._onButtonClick);
                $("input:button", this._root).bind("click.register", this._buttonClickDelegate);

                this._validateDelegate = Function.createDelegate(this, this._onValidate);
                $("input:text, input:password", this._root).bind("blur.register", this._validateDelegate);
            },
            dispose: function () {
                //Add custom dispose actions here

                $("input:button").unbind("click.register");
                this._buttonClickDelegate = null;

                $("input:text, input:password", this._root).unbind("blur.register")
                this._validateDelegate = null;

                SCS.RegisterBehavior.callBaseMethod(this, 'dispose');
            },

            _onValidate: function (e) {

                if (!this._lazyValidate)
                    this._validate()
            },

            _onButtonClick: function (e) {

                var root = this._root,
                    selector = "#" + e.target.id + "[dialog-action]";

                switch (e.target.id) {

                    case "proceedButton":

                        if (this._validate()) {

                            var pendingAction;

                            if ($(selector, root).length > 0)
                                eval("pendingAction = " + $(e.target).attr("dialog-action"));

                            if (typeof (pendingAction.defer) == "undefined" || !pendingAction.defer) {
                                this._populate();
                            }
                            else {

                                this._pendingAction = pendingAction;

                                switch (this._stepIndex) {

                                    case 0:
                                        this._createLogin();
                                        break;

                                    case 1:
                                        this._createProfile();
                                        break;
                                }
                            }
                        }
                        break;
                }
            },

            _createLogin: function () {

                var root = this._root,
                    data = {
                        username: $("#usernameEntry", root).val(),
                        password: $("#passwordEntry", root).val(),
                        emailAddress: $("#emailEntry", root).val(),
                        securityQuestion: $("#securityQuestionSelect", root).val(),
                        securityAnswer: $("#securityAnswerEntry", root).val()
                    };

                this._callService(Sys.Serialization.JavaScriptSerializer.serialize(data), "CreateUser");
            },

            _createProfile: function () {

                var host = $find(this._hostInfo.behaviorId),
                    root = this._root,
                    memData,
                    profileData = {
                        address: $("#addressEntry", root).val(),
                        city: $("#cityEntry", root).val(),
                        state: $("#stateEntry", root).val(),
                        postalCode: $("#postalCodeEntry", root).val()
                    };

                memData = host.getContentData(0);



                profileData.username = memData.username;

                this._callService(Sys.Serialization.JavaScriptSerializer.serialize(profileData), "SaveProfile");
            },

            _callService: function (json, method, successHandler, errorHandler) {

                $.ajax({
                    type: "POST",
                    url: "AjaxService.svc/" + method,
                    contentType: "application/json; charset=utf-8",
                    success: this._onServiceCallSuccess,
                    error: this._onServiceCallError,
                    dataType: "json",
                    data: json,
                    context: this
                });
            },

            _onServiceCallError: function (xhr, status, error) {

                $("#dialogMessage", this._root).text(String.format("A \"{0}\" error has occurred. {1}", status, error));
            },

            _onServiceCallSuccess: function (data, status) {

                if (data.d.success)
                    this._populate();
                else
                    $("#dialogMessage", this._root).text(data.d.message);
            },

            _populate: function () {

                if (this._pendingAction)
                    $find(this._hostInfo.behaviorId).populate(this._pendingAction);
            },

            _validate: function () {

//                $.validity.setup({
//                    outputMode: "modal",
//                    modalErrorsClickable: false
//                });

                // Start validation:    
                $.validity.start();

                var root = this._root;

                switch (this._stepIndex) {

                    case 0:
                        $("input:text", root).require();
                        $("input:password", root).require().equal("Passwords do not match");
                        break;

                    case 1:
                        $("#postalCodeEntry", root).match("integer");
                        break;
                }

                // End the validation session:    
                var result = $.validity.end();

                if (!result.valid) {
                    this._lazyValidate = false;
                    return false;
                }

                return true;
            },

            get_stepIndex: function () {
                return this._stepIndex;
            },

            set_stepIndex: function (value) {
                this._stepIndex = value;
            }
        }
        SCS.RegisterBehavior.registerClass('SCS.RegisterBehavior', Sys.UI.Behavior);

        if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

    } // execute

    if (window.Sys && Sys.loader) {
        Sys.loader.registerScript(scriptName, null, execute);
    }
    else {
        execute();
    }

})();
